package com.atguigu.dao.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.pojo.Book;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

/**
 * @author YAO
 * @create 2021-04-27 14:23
 */
public class BookDaoImpl extends BaseDao implements BookDao {

    @Override
    public int addBook(Book book) {
        String sql = "INSERT INTO t_book(`name`,`price`,`author`,`sales`,`stock`,`img_path`)\n" +
                "VALUES(?,?,?,?,?,?)";
        return update(sql,book.getName(), book.getPrice(), book.getAuthor(),
                book.getSales(), book.getStock(), book.getImg_path());
    }

    @Override
    public int deleteBookById(Integer id) {
        String sql = "DELETE FROM t_book WHERE id=?";
        return update(sql,id);
    }

    @Override
    public int updateBook(Book book) {
        String sql = "update t_book set `name`=?,`price`=?,`author`=?,`sales`=?,`stock`=?,`img_path`=?" +
                "where id=?";
        return update(sql,book.getName(), book.getPrice(), book.getAuthor(),
                book.getSales(), book.getStock(), book.getImg_path(),book.getId());
    }

    @Override
    public Book queryBookById(Integer id) {
        String sql = "select id, `name`,`price`,`author`,`sales`,`stock`,`img_path` from t_book " +
                "where id=?";
        return queryForOne(Book.class,sql,id);
    }

    @Override
    public List<Book> queryBooks() {
        String sql = "select `id`,`name`,`price`,`author`,`sales`,`stock`,`img_path` from t_book";
        return queryForList(Book.class,sql);
    }

    @Override
    public Integer queryForPageTotalCount() {
        String sql = "select count(*) from t_book";

        Number cnt = (Number) queryForSingleValue(sql);

        return cnt.intValue();
    }

    @Override
    public List<Book> queryForPageItems(int begin, Integer pageSize) {
        String sql = "select `id`,`name`,`price`,`author`,`sales`,`stock`,`img_path` from t_book limit ?,?";
        return queryForList(Book.class,sql,begin,pageSize);
    }

    @Override
    public Integer queryForPageTotalCountByPrice(int min, int max) {
        String sql = "select count(*) from t_book where price between ? and ?";

        Number cnt = (Number) queryForSingleValue(sql,min,max);

        return cnt.intValue();
    }

    @Override
    public List<Book> queryForPageItemsByPrice(int begin, int pageSize, int min, int max) {
        String sql = "select `id`,`name`,`price`,`author`,`sales`,`stock`,`img_path` from t_book " +
                "where `price` between ? and ? order by price limit ?,?";
        return queryForList(Book.class,sql,min,max,begin,pageSize);
    }
}
